import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

public class TableListServlet extends HttpServlet {



    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        System.out.println("TableListServlet init !!!");
        String path = "/jdbcConf";
        //获取数据库信息，注册watcher
        final GetJdbcConfig getJdbcConfig = GetJdbcConfig.getInstance();
        getJdbcConfig.setPath(path);
        getJdbcConfig.getFromZk();
        getJdbcConfig.subscribeDataChanges();
        //建立连接池
        ConnectionPool.getInstance();
    }

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html; charset=UTF-8");

        //从数据库连接池中获取连接
        ConnectionPool connectionPool = ConnectionPool.getInstance();
        Connection conn = connectionPool.getConnection();

        //拼接字符串
        StringBuffer sb = new StringBuffer();
        sb.append("<h1 align='center'>Databases: "+ GetJdbcConfig.getInstance().getDatabase() +"</h1>");
        sb.append("<table align='center' border='1' cellspacing='0'>\r\n");
        sb.append("<tr><td>table_name</td></tr>\r\n");
        String trFormat = "<tr><td>%s</td></tr>\r\n";
        try(final Statement sta = conn.createStatement()) {
            final ResultSet rst = sta.executeQuery("show tables");
            while (rst.next()) {
                sb.append(String.format(trFormat, rst.getString(1)));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        //归还连接
        connectionPool.returnConnection(conn);
        sb.append("</table>");
        response.getWriter().write(sb.toString());
    }
}
